package com.algorithm.onehundred2onehundredfifty;

import java.util.HashMap;
import java.util.Map;

/**
 * @author tuzhijin
 * @version Id: MajorityElement_169.java, v 0.1 2021/5/23 上午10:35 tuzhijin Exp $$
 */
public class MajorityElement_169 {

    public static void main(String[] args) {
        int[] nums = {2,2,1,1,1,2,2};
        System.out.println(majorityElement(nums));
    }

    public static int majorityElement(int[] nums) {
        Map<Integer, Integer> init = new HashMap<>();
        for (int num : nums) {
            if (init.containsKey(num)){
                Integer count = init.get(num)+1;
                init.put(num,count);
                if (count>nums.length/2){
                    return num;
                }
            }else {
                init.put(num, 1);
            }
        }
        return 0;
    }

}
